from aip import AipSpeech
import os

# 百度语音测试
# 将文字转化为pcm，再将pcm转化成文字

APP_ID = '16054657'
API_KEY = 'iOqUrnNN5Nzwjx3mfQxHcUzE'
SECRET_KEY = 'aIvKvYyTGD792ArHDAK7NObbQcuUhNMq'

client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
client.setConnectionTimeoutInMillis(60000)
client.setSocketTimeoutInMillis(60000)


def convert_text_audio(text):
    tmp_read_file = "tmp_read.pcm"
    read_file = "read.pcm"
    result = client.synthesis(text, 'zh', 1, {
        'spd': 4,
        'vol': 14,
        'per': 3
    })
    if not isinstance(result, dict):
        with open(tmp_read_file, 'wb') as f:
            f.write(result)
        os.system("ffmpeg -y -i %s -acodec pcm_s16le -f s16le -ac 1 -ar 16000 %s" %
                  (tmp_read_file, read_file))
    return read_file


def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()


def demo():
    audio_file = convert_text_audio("你好百度语音！")
    ret = client.asr(get_file_content(audio_file), 'pcm', 16000, {
        'dev_pid': 1536
    })
    print(ret)


demo()
